package com.activities;


import android.app.Activity;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TableRow;
import android.widget.TextView;

import com.Animations.AnimUtil;
import com.Data.Post;
import com.Data.Post.OnGetPicturesCompleted;
import com.Data.User;
import com.Data.User.onGetLoginCompleted;
import com.Downloaders.ThumbDownloader;
import com.Downloaders.ThumbDownloader.ThumbnailPathCompleted;
import com.Enums.BlurType;
import com.Managers.ConnectionManagerClass;
import com.Managers.FragmentManagerClass;
import com.Managers.PictureManagerClass.CreateBlurAsync;
import com.Managers.ThemeManager;
import com.Managers.UserManagerClass;
import com.TextFormat.UtilFonts;
import com.shareup.R;
import com.utils.AppConstant;
import com.utils.ShowToastClass;


public class ActivityLogin extends Activity {

    private TextView By;

    private EditText euser;

    private Button loginB;

    private RelativeLayout mainLayout;

    private EditText pass;

    private Button registerB;

    private void callForLogin() {

        if (ConnectionManagerClass.isConnection(this)) {
            String user = euser.getText().toString();
            String passw = pass.getText().toString();

            if (euser.getText().toString().isEmpty())
                this.euser.setError(getResources().getString(R.string.error_empty_fields));
            else
                if (pass.getText().toString().isEmpty())
                    this.pass.setError(getResources().getString(R.string.error_empty_fields));
                else {
                    User us = new User();
                    us.setContext(this);
                    us.setPassword(passw);
                    us.setUsername(user);
                    us.setCallbackGetLogin(new onGetLoginCompleted() {

                        @Override
                        public void Completed(User result) {

                            saveUserData(result);
                        }
                    });

                    us.execute(User.ACTION_GET_LOGIN);
                }

        }
        else {

            ShowToastClass.message(this.getResources().getString(R.string.error_no_connection_message), this);
        }
    }

    private void downloadWall(String path) {

        if (!path.equals("null") && !path.equals("-10")) {

            String[] data = path.split("#");
            path = data[1];
            final String name = data[0];

            ThumbDownloader td = new ThumbDownloader(this, path);
            td.setCompletePath(new ThumbnailPathCompleted() {

                @Override
                public void Completed(String path) {

                    CreateBlurAsync cbs = new CreateBlurAsync(BlurType.BLUR_COVER.getValue(), mainLayout, path);
                    cbs.setUserProfile(true);
                    cbs.execute();
                    //
                    By.setText(String.format(getResources().getString(R.string.string_upload_by), name));
                    AnimUtil.animateFadeIn(By);

                }
            });
            td.execute();
        }
    }

    private void getWall() {

        Post pt = new Post(Post.ACTION_GET_LIKED_PICTURE, this, null);

        pt.setCallbackGetPictures(new OnGetPicturesCompleted() {

            @Override
            public void Completed(Post[] result) {

                String path = result[0].getPathFull();

                downloadWall(path);

            }
        });
        pt.execute();
    }

    private void gotoMain() {

        Intent intent = new Intent(this, ActivityMain.class);
        startActivity(intent);
        AnimUtil.getActivityTransition(this, true);
        //
        finish();
    }

    private void inicializar() {

        FragmentManagerClass.aLogin = this;
     
        
        mainLayout = (RelativeLayout) findViewById(R.id.login_main_layout);
        euser = (EditText) findViewById(R.id.edit_login_user);
        pass = (EditText) findViewById(R.id.edit_login_pass);
        pass.setOnEditorActionListener(new EditText.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    callForLogin();
                    return true;
                }
                return false;
            }
        });
        loginB = (Button) findViewById(R.id.login_button_reg);
        registerB = (Button) findViewById(R.id.login_register_button);
        By = (TextView) findViewById(R.id.txt_by);
        By.setVisibility(View.INVISIBLE);
        //
        loginB.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                callForLogin();

            }
        });
        registerB.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                startRegisterIntent();
            }
        });
        //
        setTitleLogin();
        //
        setWallpaper();
    }

    private void saveUserData(User result) {

        if (result.getID() == 0)
            ShowToastClass.message(getResources().getString(R.string.error_no_found_user), this);
        else
            if (result.getID() == -10)
                ShowToastClass.message(getResources().getString(R.string.error_connection_timeout), this);

            else
                if (result.getID() > 0) {
                    UserManagerClass usm = new UserManagerClass(this);
                    usm.saveInfo(result);
                    gotoMain();
                }

    }

    private void setTitleLogin() {

        TextView title = new TextView(this);
        TableRow title_cont = (TableRow) findViewById(R.id.table_imgs);
        title.setText(getResources().getString(R.string.app_name));
        title.setTextSize(80);
        title.setGravity(Gravity.CENTER);
        title.setTextColor(getResources().getColor(R.color.background));
        Typeface tf = Typeface.createFromAsset(getAssets(), "font/honey.ttf");
        //
        title.setTypeface(tf);
        title_cont.addView(title);
        //

    }

    private void setWallpaper() {

        UtilFonts.setTextRegularFont(euser, loginB, pass, registerB, By);

        getWall();
    }

    private void startRegisterIntent() {

        Intent intent = new Intent(this, ActivityRegister.class);
        startActivity(intent);
        AnimUtil.getActivityTransition(this, true);
    }

    //
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        ThemeManager.setTheme(this);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        //

        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        //
        inicializar();
    }
}
